package thread;

//实现定时器

//abstract class MyTimerTask implements Runnable {
//    @Override
//    public void run() {
//
//    }
//}

import java.util.PriorityQueue;
import java.util.concurrent.Executors;

class MyTimerTask implements Comparable<MyTimerTask> {
    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    private Runnable task;

    private long time;

    public MyTimerTask(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    public long getTime() {
        return time;
    }

    public void run() {
        task.run();
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    Object lock = new Object();

    public void schedule(Runnable task, long delay) {
        synchronized (lock) {
            MyTimerTask timerTask = new MyTimerTask(task,System.currentTimeMillis() + delay);
            queue.offer(timerTask);
            lock.notify();
        }
    }

    public MyTimer() {
        Thread thread = new Thread(()->{
            while(true) {
                synchronized (lock) {
                    while (queue.isEmpty()) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
//                        continue;
                    }
                    MyTimerTask task = queue.peek();
                    if (System.currentTimeMillis() < task.getTime()) {
//                        continue;
                        try {
                            lock.wait(task.getTime() - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        task.run();
                        queue.poll();
                    }
                }
            }
        });
        thread.start();
    }
}

public class Demo38 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3");
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2");
            }
        },2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1");
            }
        },1000);

        Executors.newScheduledThreadPool(4);
    }
}
